package org.jash.demo2205.shop

import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.hyphenate.chat.ChatClient
import com.hyphenate.helpdesk.callback.Callback
import org.jash.demo2205.APIService
import org.jash.demo2205.databinding.FragmentMineBinding
import org.jash.demo2205.entity.User
import org.jash.demo2205.mvvm.BaseFragment
import org.jash.demo2205.utils.SPUtils
import org.jash.demo2205.utils.retrofit

/**
 * A simple [Fragment] subclass.
 * Use the [MineFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>() {
    lateinit var user: User
    val service = retrofit.create(APIService::class.java)
    val launcher by lazy { registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let { requireContext().contentResolver.openInputStream(it)?.readBytes() }?.let {
            viewModel.uploadIcon(it)
        }
    } }
    override fun initData() {
        launcher
        user = Gson().fromJson(SPUtils.instance.getString("user_info", ""), User::class.java)
        viewModel.uploadIconLiveData.observe(viewLifecycleOwner) {
            Toast.makeText(requireContext(), "修改头像成功", Toast.LENGTH_SHORT).show()
            user.icon = it
            binding.user = user
            SPUtils.instance.putString("user_info", Gson().toJson(user))
        }

    }

    override fun initView() {
        binding.user = user
        binding.logout.setOnClickListener {
            SPUtils.instance.putString("token", "")
            ChatClient.getInstance().logout(false, object :Callback {
                override fun onSuccess() {
                }

                override fun onError(code: Int, error: String?) {
                }

                override fun onProgress(progress: Int, status: String?) {
                }

            })
            requireActivity().finish()
        }
        binding.icon.setOnClickListener {
            launcher.launch("image/*")
        }
    }


}